package com.freexiaoyu.freevideoplay.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class NetUtil {

    /**
     * 网络连接检测
     *
     * @param ctx
     * @return
     */
    public static boolean isNetworkAvailable(Context ctx) {
        boolean netstatus = false;
        try {
            ConnectivityManager cm = (ConnectivityManager) ctx
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info = cm.getActiveNetworkInfo();
            if (info != null && info.isConnected()) {
                netstatus = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            netstatus = false;
        }
        return netstatus;
    }


    /**
     * 获取当前的网络状态 -1：没有网络     1：WIFI网络    2：wap网络    3：net网络
     *
     * @param context
     * @return
     */
    public static int getAPNType(Context context) {
        int netType = -1;
        ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo == null) {
            return netType;
        }
        int nType = networkInfo.getType();
        if (nType == ConnectivityManager.TYPE_MOBILE) {

            if (networkInfo.getExtraInfo().toLowerCase().equals("cmnet")) {
                netType = 3;
            } else {
                netType = 2;
            }
        } else if (nType == ConnectivityManager.TYPE_WIFI) {
            netType = 1;
        }
        return netType;
    }


    /**
     * 通过GPRS获取本地IP
     *
     * @return
     */
    public static String getLocalIpAddress() {
        String ip = "127.0.0.1";
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        ip = inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
            ex.printStackTrace();
        }
        return ip;

    }


    public static int ping(String host) {
        String system = (String) (System.getProperty("os.name")).toLowerCase();
        String command = "";
        if (system.indexOf("win") != -1) {
            command += "ping -w 500 " + host;// 设置500毫秒的超时
        } else if (system.indexOf("linux") != -1) {
            command += "ping -t 4 " + host; // ping 四次
        } else {
            command += "ping " + host;
        }
        int minTime = Integer.MAX_VALUE, curTime;
        try {
            Process process = Runtime.getRuntime().exec(command);
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = null;
            int count = 2, index;
            //最多只读10行
            while ((line = in.readLine()) != null && count-- != 0) {
                line = line.toLowerCase();
                System.out.println(line);
                if ((index = line.indexOf("time")) != -1) {
//                if ((index = line.indexOf("时间")) != -1) {
                    byte[] buf = line.getBytes();
                    int start = 0, end = buf.length, i, j;
                    for (i = index + 4; i < buf.length; i++) {
                        if (Character.isDigit((char) buf[i])) {
                            start = i;
                            break;
                        }
                    }
                    if (i == buf.length)
                        continue;
                    for (j = start; j < buf.length; j++) {
                        if (Character.isLetter((char) buf[j])) {
                            end = j;
                            break;
                        }
                    }
                    curTime = (int) Float.parseFloat(new String(buf, start, end - start).trim());
                    if (curTime < minTime) {
                        minTime = curTime;
                    }
                }
            }

        } catch (Exception ex) {
            return Integer.MAX_VALUE;
        }
        return minTime;
    }

    public static boolean isNetworkHasTraffic(String ip) {
        Runtime runtime = Runtime.getRuntime();
        java.lang.Process ipProcess = null;
        InputStream inputStrem = null;
        BufferedReader in = null;
        try {
            ipProcess = runtime.exec("ping -c 4 -i 0.2 -w 1 " + ip);
            inputStrem = ipProcess.getInputStream();
            in = new BufferedReader(new InputStreamReader(inputStrem));
            StringBuffer stringBuffer = new StringBuffer();
            String content = "";

            while ((content = in.readLine()) != null) {
                stringBuffer.append(content);
            }

            int exitValue = ipProcess.waitFor();

            if (exitValue == 0) {
                //网络正常且有流量
                return true;
            } else if (exitValue == 1) {
                if (stringBuffer.indexOf("100% packet loss") != -1) {
                    //状态值返回1 网络丢包严重，判断为网络未连接
                    return false;
                } else {
                    return true;
                }
            } else if (exitValue == 2) {
                // 状态值返回2  网络未连接不可用
                return false;
            } else {
                // 其他异常场景
                return false;
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (ipProcess != null) {
                ipProcess.destroy();
            }

            try {
                if (in != null) {
                    in.close();
                }
                if (inputStrem != null) {
                    inputStrem.close();
                }
            } catch (IOException e) {
            }

            runtime.gc();
        }
        return false;
    }


    // 执行ping命令并返回结果
    public static String ping2(String ipAddress) {
        StringBuilder output = new StringBuilder();
        Process process = null;
        try {
            // 使用Runtime.getRuntime().exec()方法执行ping命令
            process = Runtime.getRuntime().exec("ping -c 4 " + ipAddress);
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                output.append(line).append("\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (process != null) {
                process.destroy();  // 销毁进程
            }
        }
        return output.toString();  // 返回结果
    }

}
